package com.lizemin.socketIo.simple;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class MessageHandler {

    /**
     * 构造函数，用于定时发送消息
     *
     * @param server  SocketIOServer 实例
     */
    @Autowired
    public MessageHandler(SocketIOServer server) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(new Date());
            // 向所有连接的客户端发送时间
            server.getAllClients().forEach(client -> {
                // 往time事件发送消息，只有监听time事件的socket.io客户端才会收到这条消息
                client.sendEvent("time", currentTime);
            });
        }, 0, 1, TimeUnit.SECONDS); // 初始延迟0秒，之后每隔1秒执行
    }

    // 监听连接建立的事件
    @OnConnect
    public void onConnect(SocketIOClient client) {
        System.out.println("新客户端连接: " + client.getSessionId());
    }

    // 监听断开连接的事件
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        System.out.println("客户端断开: " + client.getSessionId());
    }

    // 监听客户端发过来的消息, 监听message事件
    @OnEvent("message")
    public void onMessage(SocketIOClient client, AckRequest ackRequest, String message) {
        System.out.println("收到消息: " + message);

        // 给所有socket-io的客户端发送消息
        client.getNamespace().getAllClients().forEach(cli -> {
            // 给message事件发消息，只有监听message事件的socket.io客户端才会收到这条消息
            cli.sendEvent("message", "服务器收到: " + message);
        });

        // 如果客户端要求服务器回复，则给客户端一个确认消息
        if (ackRequest.isAckRequested()) {
            ackRequest.sendAckData("消息已处理");
        }
    }

    // 监听onPlayGames事件
    @OnEvent("onPlayGames")
    public void onPlayGames(SocketIOClient client, AckRequest ackRequest, String message) {
        System.out.println("收到消息: " + message);
        // 给所有socket-io的客户端发送消息
        SocketIONamespace namespace = client.getNamespace();
        namespace.getAllClients().forEach(cli -> {
            // 给onPlayGames事件发消息，只有监听onPlayGames事件的socket.io客户端才会收到这条消息
            cli.sendEvent("onPlayGames", "服务器收到: " + message);
        });

        // 如果客户端要求服务器回复，则给客户端一个确认消息
        if (ackRequest.isAckRequested()) {
            // 回复客户端
            ackRequest.sendAckData("消息已处理");
        }
    }
}